package com.xyhy.core.base.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Persistable;

import com.xyhy.core.base.converter.DTOConverter;
import com.xyhy.core.base.model.dto.ObjectDTO;
import com.xyhy.core.base.service.ICrudService;

/**
 * 对象Crud的Controller基类
 *
 * @param <PO>        实体对象的类型
 * @param <ID>        ID的数据类型
 * @param <SERVICE>   Crud服务的类型
 * @param <DTO>       接口对象的类型
 * @param <CONVERTER> PO与DTO的转换器类型
 */
public abstract class CrudController<PO extends Persistable<ID>, ID, SERVICE extends ICrudService<PO, ID>,
        DTO extends ObjectDTO<ID>, CONVERTER extends DTOConverter<PO, DTO>> implements ICrudController<DTO,
        DTO, DTO, ID> {
  protected @Autowired SERVICE service;
  protected @Autowired CONVERTER converter;

  @Override
  public DTO findById(ID id) {
    return converter.convert(service.findById(id));
  }

  @Override
  public DTO add(DTO data) throws Exception {
    return this.save(data);
  }

  @Override
  public DTO update(DTO data) throws Exception {
    return this.save(data);
  }

  @Override
  public ID delete(ID id) {
    service.delete(id);
    return id;
  }

  @Override
  public List<ID> batchDelete(List<ID> ids) {
    service.deleteInBatch(ids);
    return ids;
  }

  public DTO save(DTO data) {
    PO po = converter.revert(data);
    return converter.convert(service.save(po));
  }
}
